package com.bruce.asurada.sso.config;

import feign.Response;
import feign.codec.ErrorDecoder;
import com.bruce.asurada.sso.exception.ServiceCallException;
import com.bruce.asurada.sso.util.ServiceHealthChecker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Feign 错误解码器
 * @author Bruce
 */
@Slf4j
@Component
public class FeignErrorDecoder implements ErrorDecoder {

    @Autowired
    private ServiceHealthChecker serviceHealthChecker;

    @Override
    public Exception decode(String methodKey, Response response) {
        String serviceName = "asurada-user";
        int status = response.status();
        String reason = response.reason();
        
        // 记录详细的服务调用失败信息
        serviceHealthChecker.logServiceCallFailure(serviceName, methodKey, status, reason);
        
        switch (status) {
            case 400:
                return new ServiceCallException(serviceName, methodKey, status, "请求参数错误: " + reason);
            case 401:
                return new ServiceCallException(serviceName, methodKey, status, "未授权访问: " + reason);
            case 403:
                return new ServiceCallException(serviceName, methodKey, status, "访问被禁止: " + reason);
            case 404:
                return new ServiceCallException(serviceName, methodKey, status, "服务不存在: " + reason);
            case 500:
                return new ServiceCallException(serviceName, methodKey, status, "服务内部错误: " + reason);
            case 502:
                return new ServiceCallException(serviceName, methodKey, status, "网关错误，目标服务可能未启动: " + reason);
            case 503:
                return new ServiceCallException(serviceName, methodKey, status, "服务不可用: " + reason);
            case 504:
                return new ServiceCallException(serviceName, methodKey, status, "网关超时: " + reason);
            default:
                return new ServiceCallException(serviceName, methodKey, status, "服务调用失败: " + reason);
        }
    }
}
